package com.zhongyi.controller;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileuploadController {

    @RequestMapping("/upload3")
    public String testUpload3(MultipartFile uploadFile) throws Exception {

        String path = "http://localhost:8090/uploads/";

        String filename = uploadFile.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-","");
        filename = uuid+"_"+filename;

        // 创建客户端的对象
        Client client = Client.create();

        // 和图片服务器进行连接
        WebResource webResource = client.resource(path + filename);

        // 上传文件
        webResource.put(uploadFile.getBytes());

        return "success";
    }

    @RequestMapping("/upload2")
    public String testUpload2(HttpServletRequest request, MultipartFile uploadFile) throws Exception {
        // 上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        System.out.println(path);
        // 判断，该路径是否存在
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        String picname = uploadFile.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-","");
        uploadFile.transferTo(new File(path,uuid+"_"+picname));


        return "success";
    }

    @RequestMapping("/upload1")
    public String testUpload1(HttpServletRequest request) throws Exception {
        // 上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        System.out.println(path);
        // 判断，该路径是否存在
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        // 解析request对象，获取上传文件项
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        // 遍历
        for(FileItem item:items){
            if(item.isFormField()){
                String name = item.getFieldName();
                System.out.println(name);
            }else{
                String filename = item.getName();
                String uuid = UUID.randomUUID().toString().replace("-","");
                filename = uuid+"_"+filename;
                item.write(new File(path,filename));
                item.delete();
            }
        }

        return "success";
    }
}
